<template>
  <div class="search-container">
    <form action="/">
      <van-search
        show-action
        v-model.trim="searchText"
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="$router.back()"
        @focus="isResultShow = false"
      />
    </form>
    <search-result
      v-if="isResultShow"
      :search-text="searchText"
    />
    <search-suggestion
      v-else-if="searchText"
      :search-text="searchText"
      @search="onSearch"
    />
    <search-history
      v-else
      :search-histories="searchHistories"
      @search="onSearch"
      @update-histories="searchHistories = $event"
    />
  </div>
</template>

<script>
import searchHistory from './search-history'
import searchResult from './search-result'
import searchSuggestion from './search-suggestion'
// import { setItem } from '../../utils/storage'

export default {
  name: 'indexSearch',
  components: {
    searchHistory,
    searchResult,
    searchSuggestion
  },
  data () {
    return {
      searchText: '', // 搜索输入框的内容
      isResultShow: false, // 控制搜索结果显示状态
      searchHistories: [] // 搜索历史数据
    }
  },
  methods: {
    onSearch (searchText) {
      this.searchText = searchText
      const index = this.searchHistories.indexOf(searchText)
      if (index !== -1) {
        // 把重复项删除
        this.searchHistories.splice(index, 1)
      }
      // 把最新的搜索历史记录放到顶部
      this.searchHistories.unshift(searchText)
      // 如果没有登录，则把搜索历史记录存储到本地
      // setItem('search-histories', this.searchHistories)
      this.isResultShow = true // 展示搜索结果
    },
    loadSearchHistories () {}
  }
}
</script>

<style scoped>

</style>
